from PyQt6 import QtWidgets, QtGui, QtCore


class CheckableComboBox(QtWidgets.QComboBox):
    def __init__(self, parent=None):
        super(CheckableComboBox, self).__init__(parent)
        # self.setModel(QtGui.QStandardItemModel(self))
        self.checkedItems = []
        self.qCheckBox = []
        self.Selectedrow_num = 0

        self.qLineEdit = QtWidgets.QLineEdit()
        self.qLineEdit.setReadOnly(True)
        self.status = 0

    def addItems(self, Iterable, p_str=None):
        self.items = Iterable
        qListWidget = QtWidgets.QListWidget()

        self.row_num = len(self.items)
        for i in range(self.row_num):
            self.qCheckBox.append(QtWidgets.QCheckBox())
            qItem = QtWidgets.QListWidgetItem(qListWidget)

            self.qCheckBox[i].setText(self.items[i])
            qListWidget.setItemWidget(qItem, self.qCheckBox[i])
            self.qCheckBox[i].stateChanged.connect(self.show)

        self.setLineEdit(self.qLineEdit)
        self.setModel(qListWidget.model())
        self.setView(qListWidget)

        self.view().pressed.connect(self.handleItemPressed)
        self.view().pressed.connect(self.get_all)
        self.view().pressed.connect(self.getCheckItem)

        self.setStyleSheet("""QComboBox QAbstractItemView
{
border: 1px solid rgb(161,161,161);
}
QComboBox QAbstractItemView::item
         {min-height:30px;
         padding:1px}""")

    def handleItemPressed(self, index):  # 这个函数是每次选择项目时判断状态时自动调用的，不用管（自动调用）
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

    def getCheckItem(self):
        # getCheckItem方法可以获得选择的项目列表，自动调用。
        checked_itmes = []
        for i in range(self.row_num):
            if self.qCheckBox[i].isChecked() == True:
                checked_itmes.append(self.qCheckBox[i].text())
        self.checkedItems = checked_itmes
        return checked_itmes

        # for index in range(1, self.count()):
        #     item = self.model().item(index)
        #     if item.checkState() == QtCore.Qt.Checked:
        #         if item.text() not in self.checkedItems:
        #             self.checkedItems.append(item.text())
        #     else:
        #         if item.text() in self.checkedItems:
        #             self.checkedItems.remove(item.text())
        # self.setCurrentText('str(self.checkedItems)')
        # print("self.checkedItems为：", self.checkedItems)
        # return self.checkedItems  # 实例化的时候直接调用这个self.checkedItems就能获取到选中的值，不需要调用这个方法，方法会在选择选项的时候自动被调用。

    def get_all(self):  # 实现全选功能的函数（自动调用）
        all_item = self.model().item(0)

        for index in range(1, self.count()):  # 判断是否是全选的状态，如果不是，全选按钮应该处于未选中的状态
            if self.status == 1:
                if self.model().item(index).checkState() == QtCore.Qt.Unchecked:
                    all_item.setCheckState(QtCore.Qt.Unchecked)
                    self.status = 0
                    break

        if all_item.checkState() == QtCore.Qt.Checked:
            if self.status == 0:
                for index in range(self.count()):
                    self.model().item(index).setCheckState(QtCore.Qt.Checked)
                    self.status = 1

        elif all_item.checkState() == QtCore.Qt.Unchecked:
            for index in range(self.count()):
                if self.status == 1:
                    self.model().item(index).setCheckState(QtCore.Qt.Unchecked)
            self.status = 0

    def show(self):
        show = ''
        Outputlist = self.getCheckItem()
        self.qLineEdit.setReadOnly(False)
        self.qLineEdit.clear()
        for i in Outputlist:
            show += i + ';'
        if self.Selectedrow_num == 0:
            self.qCheckBox[0].setCheckState(0)
        elif self.Selectedrow_num == self.row_num - 1:
            self.qCheckBox[0].setCheckState(2)
        else:
            self.qCheckBox[0].setCheckState(1)
        self.qLineEdit.setText(show)
        self.qLineEdit.setReadOnly(True)
